# encoding:gbk

from sgmllib import SGMLParser
import string

# 从htm文件中收集标签A
class ListName(SGMLParser):
    def __init__(self):
        SGMLParser.__init__(self)
        self.is_a = ''
        self.name = {}
        self.href = ''

    def start_a(self, attrs):
        tmp = [v for k, v in attrs if k == 'href']

        if len(tmp) < 1:
            return

        if '_25' not in tmp[0]:
            return

        self.is_a = 1
        temp = string.replace(tmp[0], '%20', ' ')
        temp = string.replace(temp, '%28', '(')
        temp = string.replace(temp, '%29', ')')

        if temp.endswith('/default.htm'):
            temp = string.replace(temp, '/default.htm', '')

        while True:
            if temp.startswith('../'):
                temp = string.replace(temp, '../', '')
            else:
                break

        if '/' in temp:
            temp = temp.split('/')[-1]

        self.href = temp
        # print self.href

    def end_a(self):
        self.is_a = ''

    def handle_data(self, text):
        if self.is_a == 1:
            self.name[self.href] = text.decode('utf8')
            # print text.decode('utf8')


if __name__ == '__main__':
    file = 'D:\\_25e7_2594_25a8 python _25e5_2592_258c opencv _25e6_25a3_2580_25e6_25b5_258b_25e5_2034d3b3ce2.htm'

    with open(file) as fn:
        content = fn.read()

    listname = ListName()
    listname.feed(content)

    # print file.split('\\')[-1]

    for k in listname.name:
        print k
        print listname.name[k]

